package org.ix.boot.mvc;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * <!-- 1. 配置监听spring-->
 * <listener>
 *     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 * </listener>
 * <!-- 1. 指定spring bean 的配置文件所在目录，扫描beans -->
 * <context-param>
 *     <param-name>contextConfigLocation</param-name>
 *     <param-value>classpath:applicationContext.xml</param-value>
 * </context-param>
 * <!-- springMVC的配置 -->
 * <servlet>
 *     <!-- 2. 创建DispatcherServlet， 注册到tomcat -->
 *     <servlet-name>spring</servlet-name>
 *     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 *     <init-param>
 *         <param-name>contextConfigLocation</param-name>
 *         <!-- 3. 配置解析 jsp，json等 -->
 *         <param-value>classpath:spring-mvc.xml</param-value>
 *     </init-param>
 * </servlet>
 * <servlet-mapping>
 *     <servlet-name>spring</servlet-name>
 *     <url-pattern>/</url-pattern>
 * </servlet-mapping>
 *
 * 基于 tomcat SPI 机制，启动是会扫描实现了 WebApplicationInitializer 接口的类，并调用其中onStartup方法
 */
public class AppInitializer implements WebApplicationInitializer {
    // tomcat 启动时调用，实现 web.xml 中spring的初始化
    @Override
    public void onStartup(ServletContext servletContext) {

        // 初始化spring容器，   调用AbstractApplicationContext.refresh()
        // 1. org.springframework.context.support.ClassPathXmlApplicationContext("applicationContext.xml");
        // 2. 第二种 没有参与spring初始化
        // 对应web.xml中第一步
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        ac.register(AppConfig.class);   // 扫描AppConfig 没有调用refresh()，所以没有完成spring的初始化

        // 对应web.xml中第二步
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/*");
    }
}
